﻿using System.Collections;

using UnityEngine;
//继承MovingObject
public class Enemy : MovingObject {

    public int playerDamage; //对玩家的伤害量

    private Animator animator;
    private Transform target; //玩家的位置信息
    private bool skipMove; //敌人能否移动

    //********** 修改开始 **********//
    //指定攻击用的音效
    public AudioClip enemyAttack1;
    public AudioClip enemyAttack2;
    //********** 修改结束 **********//

    //继承MovingObject的Start方法
    protected override void Start ( ) {

        //把自己装载到GameManager脚本中的enemyies序列里
        GameManager.instance.AddEnemyToList (this);

        //获取Animator
        animator = GetComponent<Animator> ( );
        //获取Player的位置信息
        target = GameObject.FindGameObjectWithTag ("Player").transform;
        //调用MovingObject的Start方法
        base.Start ( );
    }
    //
    protected override void AttemptMove<T> (int xDir, int yDir) {
        if (skipMove) {
            skipMove = false;
            return;
        }

        base.AttemptMove<T> (xDir, yDir);
        //移动结束了flag
        skipMove = true;
    }
    //敌方角色移动用方法　从GameManager调用
    public void MoveEnemy ( ) {
        int xDir = 0;
        int yDir = 0;
        //在同一行(x轴)时
        //Mathf.Abs: 获取距离的绝对值。
        if (Mathf.Abs (target.position.x - transform.position.x) < float.Epsilon) {
            //Player在上方+1、下方-1
            yDir = target.position.y > transform.position.y ? 1 : -1;
        } else {
            //Player在右侧+1、左侧的话-1する
            xDir = target.position.x > transform.position.x ? 1 : -1;
        }
        //范型机能　攻击対象是只有Player、型的参数就是Player
        AttemptMove<Player> (xDir, yDir);
    }
    //必须实现MovingObject的抽象方法
    protected override void OnCantMove<T> (T component) {
        //获取Player
        Player hitPlayer = component as Player;

        animator.SetTrigger ("enemyAttack"); //执行攻击动画

        //调用Player类的LoseFood 参数是 对玩家的伤害量
        hitPlayer.LoseFood (playerDamage);

        //********** 修改开始 **********//
        //把攻击用音效传递给SoundManager随机播放
        SoundManager.instance.RandomizeSfx (enemyAttack1, enemyAttack2);
        //********** 修改结束 **********//
    }
}
